﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Web;
using TweetsTranslate.MicrosoftTranslator;
using TweetsTranslate.Models;

namespace TweetsTranslate.Providers
{
    public class MicrosoftTranslateProvider
    {
        private AdmAuthentication admAuth;
        private LanguageServiceClient languageServiceClient;
        private List<string> supportedLanguages;
        public MicrosoftTranslateProvider()
        {

        }

        public void Authenticate()
        {
            admAuth = new AdmAuthentication(ConfigurationManager.AppSettings["microsoftTranslateClientId"],
                    ConfigurationManager.AppSettings["microsoftTranslateClientSecret"]);

            languageServiceClient = new MicrosoftTranslator.LanguageServiceClient();
            AdmAccessToken admToken = admAuth.GetAccessToken();
            string headerValue = "Bearer " + admToken.access_token;

            supportedLanguages = languageServiceClient.GetLanguagesForTranslate(headerValue).ToList();
            
            if (supportedLanguages == null)
            {
                supportedLanguages = new List<string>() { "en", "ro", "de" };
            }
        }

        private HttpRequestMessageProperty CreateHttpRequestMessageProperty()
        {
            AdmAccessToken admToken = admAuth.GetAccessToken();
            string headerValue = "Bearer " + admToken.access_token;

            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers.Add("Authorization", headerValue);

            return httpRequestProperty;
        }

        public string TranslateText(string text, string fromLanguage, string toLanguage)
        {
            string translationResult = string.Empty;
            using (OperationContextScope scope = new OperationContextScope(languageServiceClient.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = CreateHttpRequestMessageProperty();
                translationResult = languageServiceClient.Translate("", text, fromLanguage, toLanguage, "text/plain", "");
            }

            return translationResult;
        }

        public List<string> GetLanguages()
        {
            return supportedLanguages;
        }
    }
}